package com.webTest.Action;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.stereotype.Controller;


import com.opensymphony.xwork2.ActionSupport;
import com.webTest.Bean.PageBean;
import com.webTest.Bean.Product;
import com.webTest.Bean.Type;
import com.webTest.Service.ProductService;
import com.webTest.tools.DateUtil;
import com.webTest.tools.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

@Controller("/productAction")
public class ProductAction  extends ActionSupport implements ServletRequestAware{
	private static final long serialVersionUID = 1L;
	@Resource
	private ProductService productService;
	private HttpServletRequest request;
	public ProductService getProductService() {
		return productService;
	}
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}
	private String page;
	private String rows;
	private Product s_product;
	private Product product;
	private File path;
	private String pathFileName;
	private String productpathFileName;
	private File productpath;
	private int tid;
	private String productfile;
	private InputStream inputStream;
	private String ids;
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public InputStream getInputStream() {
		return inputStream;
	}
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public String getProductfile() {
		return productfile;
	}
	public void setProductfile(String productfile) {
		this.productfile = productfile;
	}
	public int getTid() {
		return tid;
	}
	public void setTid(int tid) {
		this.tid = tid;
	}
	public Product getS_product() {
		return s_product;
	}
	public void setS_product(Product s_product) {
		this.s_product = s_product;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public String getRows() {
		return rows;
	}
	public void setRows(String rows) {
		this.rows = rows;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public File getPath() {
		return path;
	}
	public void setPath(File path) {
		this.path = path;
	}
	public String getPathFileName() {
		return pathFileName;
	}
	public void setPathFileName(String pathFileName) {
		this.pathFileName = pathFileName;
	}
	public File getProductpath() {
		return productpath;
	}
	public void setProductpath(File productpath) {
		this.productpath = productpath;
	}
	public String getProductpathFileName() {
		return productpathFileName;
	}
	public void setProductpathFileName(String productpathFileName) {
		this.productpathFileName = productpathFileName;
	}
	/**
	 * 后台展示产品
	 * @return
	 * @throws Exception
	 */
	public String list()throws Exception{
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		List<Product> productList=productService.getProductList(s_product, pageBean);
		Iterator<Product> productIterator=productList.iterator();
		while (productIterator.hasNext()) {
			Product product = (Product) productIterator.next();
			if (product.getPath().contains(",")) {
				String newpath=product.getPath().substring(0, product.getPath().indexOf(","));
				product.setPath(newpath);
			}
		}
		long total=productService.getProductCount(s_product);
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.setExcludes(new String[] {"ParentType","children","userMachines"});
		jsonConfig.registerJsonValueProcessor(Type.class,new ObjectJsonValueProcessor(new String[]{"tid","tname"}, Type.class));
		JSONArray rows=JSONArray.fromObject(productList, jsonConfig);
		JSONObject result=new JSONObject();
		result.put("rows", rows);
		result.put("total", total);
		ResponseUtil.write(ServletActionContext.getResponse(), result);
		return null;
	}
	
	/**
	 * 后台保存修改产品
	 * @return
	 * @throws Exception
	 */
	public String savaProduct()throws Exception {	
		if(path!=null){
			if (pathFileName.trim().lastIndexOf(",")==-1) {
				String imageName=DateUtil.getCurrentDateStr();
				String realPath=ServletActionContext.getServletContext().getRealPath("/img/product");
				String imageFile=imageName+"."+pathFileName.split("\\.")[1];
				File saveFile=new File(realPath,imageFile);
				FileUtils.copyFile(path, saveFile);	
				product.setPath("img/product/"+imageFile);
			}else{
				String	[] pathFilename=pathFileName.split(", ");
				String [] paths=new String[pathFilename.length];
				for(int i=0;i<=pathFilename.length-1;i++){
					String imageName=DateUtil.getCurrentDateStr();
					String realPath=ServletActionContext.getServletContext().getRealPath("/img/product");
					String imageFile=imageName+"."+pathFilename[i].split("\\.")[1];
					File saveFile=new File(realPath,imageFile);
					FileUtils.copyFile(path, saveFile);
					paths [i]="img/product/"+imageFile;				
				}
				product.setPath(StringUtils.join(paths, ","));
			}
		}
		if (productpath!=null) {
			String realPath=ServletActionContext.getServletContext().getRealPath("/admin/product");
			File file=new File(realPath, productpathFileName);
			FileUtils.copyFile(productpath, file);
			product.setProductpath(productpathFileName);
		}
		productService.saveProduct(product);
		JSONObject result=new JSONObject();
		result.put("success", true);
		ResponseUtil.write(ServletActionContext.getResponse(), result);
		return null;
	}
	
	
	
	public String deletProduct()throws Exception {
		JSONObject result=new JSONObject();
		String []idsStr=ids.split(",");
		for(int i=0;i<idsStr.length;i++){
			Product p=productService.getID(Integer.parseInt(idsStr[i]));
			productService.deletProduct(p);
		}
		result.put("success", true);
		ResponseUtil.write(ServletActionContext.getResponse(), result);
		return null;
	}
	
	/**
	 * 产品详情
	 * @return
	 */
	public String detailProduct(){
		List<Product> list=productService.getProductTID(tid);
		request.setAttribute("list",list);
		return "detail";
	}
	
	public String typeProduct(){
		List<Type> list=productService.getTypeTID(tid);
		Map<String, List<Product>>  m=new HashMap<>();
		for(int i=0;i<list.size();i++){
			List<Product> listcount=productService.getProductTID(list.get(i).getTid());	
			m.put(list.get(i).getTname(), listcount);
		}
		request.setAttribute("m",m);
		return "type";
		
	}
	
	/**
	 * 下载产品
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public  String download() throws IOException,FileNotFoundException {
     String downloadpath="/root/apache-tomcat-7.0.81/webapps/OfficialWebsite/admin/product";
     File file=new File(downloadpath, productfile);
     inputStream=new FileInputStream(file);
     return "download";
    }
	
	
	
	public String getAllProduct() throws Exception{
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("id", "");
		jsonObject.put("name", "请选择");
		jsonArray.add(jsonObject);
		List<Product> list=productService.getAllProduct();
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.setIgnoreDefaultExcludes(false);         
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
		jsonConfig.setExcludes(new String[]{"userMachines","type"});
		JSONArray rows=JSONArray.fromObject(list, jsonConfig);
		jsonArray.addAll(rows);
		ResponseUtil.write(ServletActionContext.getResponse(), jsonArray);
		return null;
	}

	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
	}

}
